import * as THREE from 'three';
import gsap from 'gsap';

// 轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; 

/**
 * Cursor
 */
const cursor = {
    x: 0,
    y: 0
}
window.addEventListener('mousemove', (event) => {
    cursor.x = event.clientX / Sizes.width - 0.5
    cursor.y = -(event.clientY / Sizes.height - 0.5)
})

// Canvas
const canvas = document.querySelector("canvas.webgl");

// Scene
const scence = new THREE.Scene();

// Object
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({
    color: '#ff0000',
    // wireframe:true
})
const mesh = new THREE.Mesh(geometry, material);
scence.add(mesh)


// Sizes
const Sizes = {
    width: 800,
    height: 600
}


// Camera 
// 透视相机就是  物体离得近变大，离远变小    角度（45~75度较为合适）  宽/高   near  far(太小会导致看不全    太大看的太多，比如我们看一个村子，村子后面的山不需要看见，far需要一个合适的值)
const camera = new THREE.PerspectiveCamera(75, Sizes.width / Sizes.height, 1, 100)
// 正交相机   远近大小不变
// const aspectRation = Sizes.width / Sizes.height
// const camera = new THREE.OrthographicCamera(-1 * aspectRation,1 * aspectRation,1,-1,0.1,100)

// 相机的初始位置在（0，0，0）中心点，看不见物体，移动相机
camera.position.z = 3

scence.add(camera)


// Controls
const controls  = new OrbitControls(camera,canvas);
controls.enableDamping = true  //添加阻尼效果  修改之后需要update
// controls.target.y = 1
// controls.update()



// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas,
})
renderer.setSize(Sizes.width, Sizes.height);



// Time
let time = Date.now();
// Animation
const tick1 = () => {
    // Time
    const currentTime = Date.now()
    const deltaTime = currentTime - time;
    time = currentTime;
    console.log(deltaTime)  //帧数越高的设备   deltaTime越小

    // Update Objects
    mesh.rotation.y += 0.002 * deltaTime     //保证物体在不同的帧数下 旋转的速度一样

    // Render
    renderer.render(scence, camera);
    window.requestAnimationFrame(tick)
}

// gsap
// gsap.to(mesh.position, { duration: 1, delay: 1, x: 2 })
// gsap.to(mesh.position, { duration: 1, delay: 2, x: 0 })

// clock解决不同设备的帧数问题
const clock = new THREE.Clock()
const tick = () => {

    // // clock
    // const elapsedTime = clock.getElapsedTime();
    // // Update Objects
    // mesh.rotation.y = elapsedTime     

    // Update Camera
    // camera.position.x = Math.sin(cursor.x * Math.PI * 2) * 3
    // camera.position.z = Math.cos(cursor.x * Math.PI * 2) * 3
    // camera.position.y = cursor.y * 5
    // camera.lookAt(mesh.position)

    controls.update()
    // Render
    renderer.render(scence, camera);
    window.requestAnimationFrame(tick);
}


tick()